__author__ = 'cloud'

from django.core import urlresolvers
from django.contrib.contenttypes.models import ContentType
from django.forms import BooleanField
from django import template
register = template.Library()

@register.filter(name='admin_add_url', is_safe=True)
def admin_add_url(formset):
    try:
        content_type = ContentType.objects.get_for_model(formset.formset.model)
        return urlresolvers.reverse("admin:%s_%s_add" % (content_type.app_label, content_type.model));
    except:
        return ""

@register.filter(name='get_type', is_safe=True)
def get_type(bf):
    if hasattr(bf.field, 'choices'):
        return 'choice'
    elif isinstance(bf.field, BooleanField):
        return 'boolean'
    else:
        return ''

@register.filter(name='render_choice', is_safe=True)
def render_choice(boundfield):
    value = boundfield.data if boundfield.data is not None else boundfield.form.initial.get(boundfield.name)
    if value is None:
        return u''
    return dict(boundfield.field.choices).get(value, u'')